package com.webinsky.web.resource;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.webinsky.site.domain.Site;
import com.webinsky.site.service.SiteManagement;
import com.webinsky.web.data.Response;
import com.webinsky.web.data.SiteActiveForm;
import com.webinsky.web.data.SiteForm;

import reactor.core.publisher.Mono;

@Component
public class SiteResource {
	@Autowired
	private SiteManagement siteManagement;
	
	public Mono<ServerResponse> getSites(ServerRequest request){
		List<Site> sites = siteManagement.getSites();
		return ServerResponse.ok().syncBody(Response.create(sites, Response.STATUS_OK, "")); 
	}
	
	public Mono<ServerResponse> enableDisableSite(ServerRequest request){
		return request.bodyToMono(SiteActiveForm.class).flatMap( data -> {
			int siteId = data.id;
			boolean actived = data.isActived;
			siteManagement.enDisable(siteId, actived);
			return ServerResponse.ok().syncBody(Response.create("", Response.STATUS_OK, ""));
		});
	}
	
	public Mono<ServerResponse> createSite(ServerRequest request){
		return request.bodyToMono(SiteForm.class).flatMap( data -> {
			Site site = new Site();
			site.setSiteDescription(data.description);
			site.setSiteName(data.name);
			site.setSiteUrl(data.url);
			siteManagement.create(site);
			return ServerResponse.ok().syncBody(Response.create(site.getId(), Response.STATUS_OK, ""));
		});
	}
}
